<?php


namespace App\Http\Controllers\cms;


use App\Engine\BaseController;
use App\Engine\map\Map;
use App\Exceptions\ApiException;
use App\Http\service\CommonService;
use App\Models\Appointment;
use App\Models\Custom;
use App\Models\Floor;
use App\Models\House;
use App\Models\Image as ImageModel;
use App\Models\Property;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use function app\Utils\go;
use App\Models\TxLog as TxLogModel;

class Common extends BaseController
{

    /**坐标转换详细地址
     * @return array
     */
    public function map_regeo()
    {
        $res=(new Map())->regeo($this->post["position"]);
        return go($res);
    }

    /**
     * 核销红包
     */
    public function hx_red_pakage()
    {
        $user=User::where("phone",$this->post["phone"])->first();
        if (!$user)
            throw new ApiException("该号码未绑定");
        if($user["balance"]<$this->post["price"])
            throw new ApiException("余额不足");
        DB::beginTransaction();
        try {
            $user->decrement("balance",$this->post["price"]);
            $create=[
                "uid"=>$user["id"],
                "price"=>$this->post["price"],
                "state"=>1
            ];
            $res=TxLogModel::create($create);
            DB::commit();
            return go($res);
        }catch (\Exception $exception){
            DB::rollBack();
        }
    }

    public function uploads_image()
    {
        $path=$this->request->file('img')->store("uploads/upimage");
        $res=ImageModel::create(["url"=>$path]);
        return go($res);
    }

    public function uploads_video()
    {
        $path=$this->request->file('video')->store("uploads/video");
        return go(["path"=>$path]);
    }

    /**经纬度坐标转换
     * @return array
     */
    public function regeo()
    {
        $position=$this->post["position"];
        return go((new CommonService())->regeo($position));
    }

    /**
     * 数据统计
     */
    public function statistics()
    {
        $Appointment=new Appointment();
        $data=array();
        $data[]=[
            "label"=>"用户",
            "value"=>User::count(),
            "tip"=>""
        ];
        $data[]=[
            "label"=>"预约",
            "value"=>$Appointment->count(),
            "tip"=>$Appointment->where("state",0)->count()
        ];

        $data[]=[
            "label"=>"顾问",
            "value"=>Custom::count(),
            "tip"=>""
        ];

        $data[]=[
            "label"=>"楼栋",
            "value"=>Property::count(),
            "tip"=>""
        ];

        $data[]=[
            "label"=>"楼层",
            "value"=>Floor::count(),
            "tip"=>""
        ];

        $data[]=[
            "label"=>"房屋",
            "value"=>House::count(),
            "tip"=>""
        ];

        $res["panel"]=$data;
        return go($res);
    }
}
